package com.hans.scala

import java.io.File
import scala.io.Source

object FileTest {
  def grep(pattern: String) = {
    val filesHere = new File("src/main/java/com/hans").listFiles()
    for {
      file <- filesHere
      if file.getName.contains(".scala") && file.getName.trim.matches(pattern)
      line <- fileLines(file)
    } println(file + ":" + line.trim)
  }

  def fileLines(file: File) =
    Source.fromFile(file).getLines().toList

  //制造新集合
  def testForYield() {
    val filesHere = new File("src/main/java/com/hans").listFiles()
    val forLines = {
      for {
        file <- filesHere
        if file.getName.contains("FileTest.scala")
        line <- fileLines(file)
        trimmed = line.trim
        if trimmed.matches(".*for.*")
      } yield trimmed
    }
    printArrayLn(forLines)
  }

  def printArrayLn(aa: Array[String]) {
    for (arg <- aa)
      println(arg)
  }


  //########################################################################################################

  def main(args: Array[String]) {
    println(fileLines(new File("src/main/scala/com/hans/scala/FileTest.scala"))
      .reduceLeft((a: String, b) => { if (a.length > b.length()) a else b }))
    //    grep(".*FileTest.*")
    //    testForYield()
  }
}
